<template>
  <div class="user-management">
    <el-card class="box-card" :body-style="{ padding: '0' }">
      <div class="header-container">
        <h2>用户管理</h2>
      </div>
      <el-table
        :data="userList"
        style="width: 100%; background-color: transparent !important;"
        v-loading="loading"
        element-loading-text="正在加载用户数据..."
        element-loading-custom-class="custom-loading"
        :border="false"
        :cell-style="{backgroundColor: 'transparent', border: 'none'}"
        :header-cell-style="{backgroundColor: 'transparent', border: 'none'}"
        class="transparent-table"
        align="center"
        header-align="center"
      >
        <el-table-column 
          prop="id" 
          label="ID" 
          min-width="60"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="String(scope.row.id)" placement="top" effect="light">
              <span>{{ truncateText(scope.row.id) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column 
          prop="username" 
          label="用户名" 
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="String(scope.row.username)" placement="top" effect="light">
              <span>{{ truncateText(scope.row.username) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column 
          prop="email" 
          label="邮箱" 
          min-width="180"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="String(scope.row.email)" placement="top" effect="light">
              <span>{{ truncateText(scope.row.email) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column 
          prop="is_active" 
          label="激活状态" 
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '已激活' : '未激活' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="is_staff" 
          label="职员状态" 
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_staff ? 'primary' : 'info'">
              {{ scope.row.is_staff ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="is_superuser" 
          label="超级用户" 
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="`实际值: ${String(scope.row.is_superuser)}`" placement="top" effect="light">
              <el-tag :type="scope.row.is_superuser ? 'warning' : 'info'">
                {{ scope.row.is_superuser ? '是' : '否' }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column 
          prop="identity" 
          label="身份" 
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="String(getIdentityName(scope.row.identity))" placement="top" effect="light">
              <span>{{ getIdentityName(scope.row.identity) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column 
          prop="date_joined" 
          label="注册日期" 
          min-width="160"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="String(scope.row.date_joined)" placement="top" effect="light">
              <span>{{ truncateText(scope.row.date_joined) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column 
          prop="last_login" 
          label="最后登录" 
          min-width="160"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip :content="String(scope.row.last_login)" placement="top" effect="light">
              <span>{{ truncateText(scope.row.last_login) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 添加空状态插槽 -->
        <template slot="empty">
          <EmptyState />
        </template>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import EmptyState from '@/components/EmptyState.vue'

export default {
  name: 'UserManagement',
  components: {
    EmptyState
  },
  data() {
    return {
      userList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      fetchTimer: null, // 添加防抖定时器
      hasError: false   // 添加错误状态标志
    }
  },
  created() {
    this.fetchUsers()
    
    // 添加全局错误处理
    window.addEventListener('error', this.handleGlobalError)
  },
  beforeDestroy() {
    // 清除定时器，防止内存泄漏
    if (this.fetchTimer) {
      clearTimeout(this.fetchTimer);
    }
    
    // 移除全局错误处理
    window.removeEventListener('error', this.handleGlobalError)
  },
  // 添加错误捕获钩子
  errorCaptured(err, vm, info) {
    console.error('组件错误:', err, info)
    this.hasError = true
    // 返回 false 防止错误继续向上传播
    return false
  },
  methods: {
    // 全局错误处理函数
    handleGlobalError(event) {
      console.error('捕获到全局错误:', event.error)
      // 可以根据需要处理错误，例如显示提示或记录日志
    },
    // 使用防抖包装的获取用户数据方法
    fetchUsers() {
      // 清除之前的定时器，实现防抖
      if (this.fetchTimer) {
        clearTimeout(this.fetchTimer);
      }
      
      this.fetchTimer = setTimeout(() => {
        this.doFetchUsers();
      }, 300); // 300ms防抖
    },
    
    // 实际执行获取用户数据的方法
    doFetchUsers() {
      // 如果已经在加载中，则不重复请求
      if (this.loading) return;
      
      this.loading = true;
      // 不再显示通知提示
      
      console.log('开始获取用户列表数据...');
      
      // 添加更详细的调试信息
      const apiUrl = '/api/users/';
      console.log('请求API地址:', apiUrl);
      
      // 检查网络状态
      if (!navigator.onLine) {
        this.$message.error('网络连接已断开，请检查网络后重试');
        this.loading = false;
        return;
      }
      
      // 构建查询参数
      const params = {
        page: this.currentPage,
        page_size: this.pageSize,
        // 添加可能的其他参数，适配后端API
        pageNum: this.currentPage,  // 有些后端使用 pageNum
        pageSize: this.pageSize     // 有些后端使用 pageSize
      };
      
      axios.get(apiUrl, {
        params,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
        },
        // 设置超时时间
        timeout: 20000
      })
        .then(response => {
          console.log('获取用户数据成功:', response);
          // 适配不同的返回格式
          if (response.data && response.data.data && Array.isArray(response.data.data)) {
            // 适配 { data: [...], msg: "xxx" } 的格式
            this.userList = response.data.data;
            this.total = response.data.data.length;
          } else if (response.data && response.data.results) {
            // 适配 { results: [...], count: ... } 的格式
            this.userList = response.data.results;
            this.total = response.data.count || response.data.results.length;
          } else if (Array.isArray(response.data)) {
            // 适配直接返回数组的格式
            this.userList = response.data;
            this.total = response.data.length;
          } else {
            this.userList = [];
            this.total = 0;
            console.warn('返回的数据格式不符合预期:', response.data);
          }
        })
        .catch(error => {
          console.error('获取用户数据失败:', error);
          
          // 根据错误类型提供不同的错误信息
          if (error.response) {
            // 服务器返回了错误状态码
            const statusCode = error.response.status;
            let errorMsg = '';
            
            // 尝试从响应中提取错误信息
            if (error.response.data) {
              if (typeof error.response.data === 'string') {
                errorMsg = error.response.data;
              } else if (error.response.data.msg) {
                errorMsg = error.response.data.msg;
              } else if (error.response.data.message) {
                errorMsg = error.response.data.message;
              } else if (error.response.data.error) {
                errorMsg = error.response.data.error;
              }
            }
            
            if (statusCode === 401) {
              this.$message.error('用户未授权或登录已过期，请重新登录');
              // 可以选择跳转到登录页
              // this.$router.push('/');
            } else if (statusCode === 403) {
              this.$message.error('您没有权限访问用户管理功能');
            } else if (statusCode === 404) {
              this.$message.error('找不到请求的资源');
            } else if (statusCode >= 500) {
              this.$message.error(`服务器错误，请稍后重试${errorMsg ? ': ' + errorMsg : ''}`);
            } else {
              this.$message.error(`请求错误 (${statusCode})${errorMsg ? ': ' + errorMsg : ': 未知错误'}`);
            }
          } else if (error.request) {
            // 请求发送了但没有收到响应
            this.$message.error('服务器无响应，请稍后重试');
          } else if (error.message.includes('timeout')) {
            // 请求超时
            this.$message.error('请求超时，请稍后重试');
          } else {
            // 其他错误
            this.$message.error('请求失败: ' + error.message);
          }
          
          this.userList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
          // 不再需要关闭加载提示
          
          // 如果没有数据，显示提示
          if (this.userList.length === 0) {
            this.$nextTick(() => {
              // 使用 nextTick 确保在 DOM 更新后显示提示
              setTimeout(() => {
                if (this.userList.length === 0) {
                  this.$message.info('暂无用户数据');
                }
              }, 100);
            });
          }
        });
    },
    // 身份值转换函数
    getIdentityName(identity) {
      // 处理空值或未定义的情况
      if (identity === null || identity === undefined) return '未设置'
      
      // 先将identity转为字符串，确保可以作为key使用
      const identityStr = String(identity)
      
      const identityMap = {
        'test_director': '测试总监',
        'test_manager': '测试经理',
        'test_supervisor': '测试主管',
        'test_leader': '测试组长',
        'senior_test_engineer': '资深测试工程师',
        'advanced_test_engineer': '高级测试工程师',
        'test_engineer': '测试工程师',
        'junior_test_engineer': '初级测试工程师'
      }
      
      return identityMap[identityStr] || identityStr || '未设置'
    },
    truncateText(text) {
      if (text === null || text === undefined) return ''
      const str = String(text) // 确保转换为字符串
      return str.length > 15 ? str.substring(0, 12) + '...' : str
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchUsers()
    },
    handleEdit(row) {
      // 处理编辑用户逻辑
      this.$message.info(`编辑用户: ${row.username}`)
    },
    handleDelete(row) {
      this.$confirm('确认删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 处理删除用户逻辑
        this.$message.success(`删除用户: ${row.username}`)
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.user-management {
  margin: 0;
  padding: 0;
  height: 100%;
}

.box-card {
  margin: 0;
  height: 100%;
  border-radius: 0;
  background-color: transparent !important;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  margin-top: 13px;
  padding: 0 30px;
}

.header-container h2 {
  font-weight: bold;
  margin-left: 0;
  font-size: 24px;
}

.pagination-container {
  padding: 10px;
  text-align: center;
}

/* 移除表格所有边框和背景色 */
.transparent-table.el-table {
  background-color: transparent !important;
}

.transparent-table.el-table::before,
.transparent-table.el-table::after {
  display: none;
}

.transparent-table.el-table .el-table__header-wrapper,
.transparent-table.el-table .el-table__body-wrapper {
  background-color: transparent !important;
}

.transparent-table.el-table .el-table__header th.el-table__cell {
  background-color: transparent !important;
  border: none !important;
}

.transparent-table.el-table .el-table__body td.el-table__cell {
  background-color: transparent !important;
  border: none !important;
}

.transparent-table.el-table .el-table__body tr:hover > td.el-table__cell {
  background-color: transparent !important;
}

.transparent-table.el-table .el-table__body tr.hover-row > td.el-table__cell {
  background-color: transparent !important;
}

.transparent-table.el-table .el-table__body tr.el-table__row--striped > td.el-table__cell {
  background-color: transparent !important;
}

/* 移除卡片边框和背景 */
:deep(.el-card) {
  border: none !important;
  background-color: transparent !important;
}

:deep(.el-card__body) {
  padding: 0 !important;
  background-color: transparent !important;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-image {
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
  opacity: 0.6;
}

.empty-text {
  font-size: 14px;
  color: #909399;
  margin-bottom: 15px;
}
</style>

<!-- 添加全局样式 -->
<style>
/* 自定义加载样式 */
.custom-loading .el-loading-spinner .circular {
  display: none;
}

.custom-loading .el-loading-spinner::before {
  content: '';
  display: block;
  width: 50px;
  height: 50px;
  background: url(../assets/loading.png) no-repeat center center;
  background-size: contain;
  animation: rotate 1.5s linear infinite;
  margin: 0 auto;
}

/* 自定义加载文字样式 */
.custom-loading .el-loading-spinner .el-loading-text {
  color: #000000 !important; /* 黑色文字 */
  margin-top: 10px !important; /* 与图标保持10px距离 */
  font-size: 14px;
}

/* 深色主题下加载文字样式 */
.theme-dark .custom-loading .el-loading-spinner .el-loading-text {
  color: #ffffff !important; /* 白色文字 */
}

/* 深色主题下更好的提示层样式 */
.theme-dark .el-tooltip__popper.is-light {
  background-color: #333 !important;
  color: #eee !important;
  border-color: #444 !important;
}

.theme-dark .el-tooltip__popper.is-light .popper__arrow,
.theme-dark .el-tooltip__popper.is-light .popper__arrow::after {
  border-top-color: #333 !important;
  border-bottom-color: #333 !important;
}

/* 保持深色主题下标签颜色不变 */
.theme-dark .el-tag.el-tag--success,
.theme-dark .el-tag.el-tag--warning,
.theme-dark .el-tag.el-tag--danger,
.theme-dark .el-tag.el-tag--info,
.theme-dark .el-tag.el-tag--primary {
  background-color: inherit !important;
  color: inherit !important;
  border-color: inherit !important;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
